import request from './lib/request'
import cheerio from 'cheerio'
// import moment from 'moment'
import model from './model'

import event from './lib/event'

async function crawler3(startTime, endTime, start) {
  const response = await request({
    methods: 'get',
    url: '/manage/apUser/toAppSuccess',
    params: {
      start: start,
      verifyStartDate: startTime,
      verifyEndDate: endTime
    }
  })

  var $ = cheerio.load(response)

  const page = $('.table tbody').find('tr').map(function() {
    let href = $($(this).find('td').eq(0).first().html()).attr('href')
    let id = href.substring(href.indexOf('?id=') + 4)
    const row = $(this).find('td').map(function(item) {
      return $(this).text().replace(/(^\s*)|(\s*$)/g, '')
    })
    return {
      id: id,
      nickName: row[0], // 客户名称/公司名称
      phone: row[1], // 联系电话
      customerType: row[2], // 用户类型
      drivingLicenceEndTime: row[3], // 驾驶证到期时间
      customerStatus: row[4], // 客户状态
      registerTime: row[5], // 注册时间
      submitAuditingTime: row[6], // 提交审核时间
      auditingTime: row[7], // 审核时间
      auditor: row[8], // 审核人
      userGroup: row[9], // 用户群组
      grabPosition: 'toAppSuccess'
    }
  })

  for (let i = 0; i < page.length; i++) {
    const element = page[i]
    await model.insert(element)
    event.emit('processed')
  }

  let nextStart = start - 20
  if (nextStart > 0) {
    crawler3(startTime, endTime, nextStart)
  } else if (start !== 0) {
    crawler3(startTime, endTime, 0)
  }
}

async function crawler2(startTime, endTime) {
  const response = await request({
    methods: 'get',
    url: '/manage/apUser/toAppSuccess',
    params: {
      verifyStartDate: startTime,
      verifyEndDate: endTime
    }
  })

  var $ = cheerio.load(response)
  const temp = $('.pager').text().match(/[\d]+/g)
  event.emit('total', parseInt(temp[0]))
  crawler3(startTime, endTime, temp[0] - 20)
}

function crawler(startTime) {
  // crawler2(startTime, moment().format('YYYY-MM-DD HH:MM:SS'))
  crawler2(startTime, null)
}

export default crawler
